<template>
  <div class="flight-task" :style="[taskStyle]">
    <div class="task-item">
      <div class="task-item-label">任务航线：</div>
      <el-select
        size="mini"
        style="width: 220px"
        v-model="task.flypath"
        placeholder="请选择需要创建任务的航线"
        clearable
        @change="selectPaths"
      >
        <el-option
          v-for="path in paths"
          :key="path.value"
          :label="path.label"
          :value="path.value"
        >
        </el-option>
      </el-select>
    </div>
    <div class="task-item">
      <div class="task-item-label">选择日期：</div>
      <el-date-picker
        size="mini"
        v-model="task.flightdate"
        placeholder="请选择日期"
        value-format="yyyy-MM-dd"
      >
      </el-date-picker>
    </div>
    <div class="task-item">
      <div class="task-item-label">开始时间：</div>
      <el-time-picker
        size="mini"
        value-format="HH:mm:ss"
        v-model="task.starttime"
        placeholder="请选择开始时间"
        @change="changeStart"
      >
      </el-time-picker>
    </div>
    <div class="task-item">
      <div class="task-item-label">结束时间：</div>
      <el-time-picker
        size="mini"
        value-format="HH:mm:ss"
        v-model="task.endtime"
        placeholder="结束时间"
        :readonly="true"
      >
      </el-time-picker>
    </div>

    <div class="task-item-btn">
      <div class="item-btn" @click="createflytask">创建飞行任务</div>
      <div class="item-btn" @click="cancel">取消创建</div>
    </div>
  </div>
</template>

<script>
import { getFlights, getFlypaths } from '@/network/static.js'

export default {
  name: 'ldFlightTask',
  props: {
    pathUrl: {
      type: String,
      default: 'http://39.105.98.235:8090/',
    },
    taskStyle: {
      type: [Object, Array],
      default: () => ({ background: '#073968a1' }),
    },
  },
  data() {
    return {
      task: {
        flightid: '',
        starttime: '',
        endtime: '',
        flypath: '',
        flightdate: '',
      },
      paths: [],
      totalDuration: 0,
    }
  },
  mounted() {
    this.initTask()
  },
  methods: {
    async initTask() {
      var res = await getFlypaths(this.pathUrl)
      if (res && res.data) {
        const data = res.data
        for (let i = 0; i < data.length; i++) {
          const pathss = {
            value: data[i].id,
            label: data[i].path.name,
            data: data[i],
          }
          this.paths.push(pathss)
        }
      }
    },
    selectPaths(e) {
      for (let i = 0; i < this.paths.length; i++) {
        const pathsChild = this.paths[i].data.path
        if (e === this.paths[i].value) {
          this.duration = this.computedTime(pathsChild.positionData)
        }
      }
    },
    changeStart(e) {
      this.task.endtime = this.calculateEndTime(e)
    },
    createflytask() {
      this.$emit('on-created-task', this.task)
    },
    cancel() {
      this.task = {
        flightid: '',
        starttime: '',
        endtime: '',
        flypath: '',
        flightdate: '',
      }
      this.paths = []
      this.totalDuration = 0
      this.$emit('on-cancel-task', '')
    },
    computedTime(data) {
      let totalTime = 0
      for (let i = 0; i < data.length - 1; i++) {
        const points = data[i]
        const points1 = data[i + 1]
        const distance = this.calculate_3d_distance(
          points.longitude,
          points.latitude,
          points.height,
          points1.longitude,
          points1.latitude,
          points1.height
        )
        const speeds = points.properties.speed ? points.properties.speed : 15
        const time = distance / speeds
        totalTime += time
      }

      //计算停留总时间
      for (let j = 0; j < data.length; j++) {
        const hoveringtime = data[j].properties.hoveringtime
        totalTime += Number(hoveringtime)
      }
      return totalTime
    },
    calculate_3d_distance(lon1, lat1, h1, lon2, lat2, h2) {
      const point1 = Cesium.Cartesian3.fromDegrees(lon1, lat1, h1)
      const point2 = Cesium.Cartesian3.fromDegrees(lon2, lat2, h2)
      const distance = Cesium.Cartesian3.distance(point1, point2) // 返回单位：米
      return distance
    },
    calculateEndTime(startTime) {
      // 拆分开始时间为时、分、秒
      const [startH, startM, startS] = startTime.split(':').map(Number)
      const baseDate = new Date(1970, 0, 1, startH, startM, startS)

      // 添加持续时间（秒→毫秒）
      const endDate = new Date(
        baseDate.getTime() + Math.ceil(this.duration) * 1000
      )

      // 格式化为 HH:mm:ss
      return [
        endDate.getHours().toString().padStart(2, '0'),
        endDate.getMinutes().toString().padStart(2, '0'),
        endDate.getSeconds().toString().padStart(2, '0'),
      ].join(':')
    },
  },
}
</script>

<style scoped>
.flight-task {
  position: absolute;
  bottom: 20px;
  color: #fff;
  left: 20px;
  padding: 5px 10px;
  border: solid #0e60af 2px;
  border-radius: 10px;
}
.task-item {
  display: flex;
  align-items: center;
  margin: 5px 0;
}

.task-item-btn {
  display: flex;
  align-items: center;
  margin: 20px 0 5px;
  justify-content: flex-end;
  gap: 20px;
}
.item-btn {
  color: #fff;
  background-color: #409eff75;
  border: 1px solid #409eff;
  padding: 5px 15px;
  /* box-sizing: border-box; */
  font-size: 12px;
  border-radius: 3px;
  cursor: pointer;
}

.item-btn:hover {
  background: #66b1ff;
  border-color: #66b1ff;
  color: #fff;
}

::v-deep .el-input__inner {
  background-color: #ffffff00;
  border: 1px solid #dcdfe6;
  color: #fff;
}
</style>